summaryrefslogtreecommitdiff
path: root/plugins/hg4idea/src/org/zmlx/hg4idea/provider/commit/HgCheckinEnvironment.java
blob: 06b74148156ed15c8cdb521fab5176c9575dba43 (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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright 2008-2010 Victor Iacoban
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
package org.zmlx.hg4idea.provider.commit;

import com.intellij.dvcs.DvcsCommitAdditionalComponent;
import com.intellij.dvcs.push.ui.VcsPushDialog;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.FunctionUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.PairConsumer;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.*;
import org.zmlx.hg4idea.action.HgActionUtil;
import org.zmlx.hg4idea.command.*;
import org.zmlx.hg4idea.execution.HgCommandException;
import org.zmlx.hg4idea.execution.HgCommandExecutor;
import org.zmlx.hg4idea.execution.HgCommandResult;
import org.zmlx.hg4idea.repo.HgRepository;
import org.zmlx.hg4idea.repo.HgRepositoryManager;
import org.zmlx.hg4idea.util.HgUtil;

import java.util.*;

public class HgCheckinEnvironment implements CheckinEnvironment {

  private final Project myProject;
  private boolean myNextCommitIsPushed;
  private boolean myNextCommitAmend; // If true, the next commit is amended

  public HgCheckinEnvironment(Project project) {
    myProject = project;
  }

  public RefreshableOnComponent createAdditionalOptionsPanel(CheckinProjectPanel panel,
                                                             PairConsumer<Object, Object> additionalDataConsumer) {
    myNextCommitIsPushed = false;
    return new HgCommitAdditionalComponent(myProject,panel);
  }

  public String getDefaultMessageFor(FilePath[] filesToCheckin) {
    return null;
  }

  public String getHelpId() {
    return null;
  }

  public String getCheckinOperationName() {
    return HgVcsMessages.message("hg4idea.commit");
  }

  @SuppressWarnings({"ThrowableInstanceNeverThrown"})
  public List<VcsException> commit(List<Change> changes,
                                   String preparedComment,
                                   @NotNull NullableFunction<Object, Object> parametersHolder,
                                   Set<String> feedback) {
    List<VcsException> exceptions = new LinkedList<VcsException>();
    Map<VirtualFile, Set<HgFile>> repositoriesMap = getFilesByRepository(changes);
    for (Map.Entry<VirtualFile, Set<HgFile>> entry : repositoriesMap.entrySet()) {

      VirtualFile repo = entry.getKey();
      Set<HgFile> selectedFiles = entry.getValue();

      HgCommitCommand command = new HgCommitCommand(myProject, repo, preparedComment, myNextCommitAmend);
      
      if (isMergeCommit(repo)) {
        //partial commits are not allowed during merges
        //verifyResult that all changed files in the repo are selected
        //If so, commit the entire repository
        //If not, abort

        Set<HgFile> changedFilesNotInCommit = getChangedFilesNotInCommit(repo, selectedFiles);
        boolean partial = !changedFilesNotInCommit.isEmpty();


        if (partial) {
          final StringBuilder filesNotIncludedString = new StringBuilder();
          for (HgFile hgFile : changedFilesNotInCommit) {
            filesNotIncludedString.append("<li>");
            filesNotIncludedString.append(hgFile.getRelativePath());
            filesNotIncludedString.append("</li>");
          }
          if (!mayCommitEverything(filesNotIncludedString.toString())) {
            //abort
            return exceptions;
          }
          //firstly selected changes marked dirty in CommitHelper -> postRefresh, so we need to mark others
          VcsDirtyScopeManager dirtyManager = VcsDirtyScopeManager.getInstance(myProject);
          for (HgFile hgFile : changedFilesNotInCommit) {
            dirtyManager.fileDirty(hgFile.toFilePath());
          }
        }
        // else : all was included, or it was OK to commit everything,
        // so no need to set the files on the command, because then mercurial will complain
      } else {
        command.setFiles(selectedFiles);
      }
      try {
        command.execute();
      } catch (HgCommandException e) {
        exceptions.add(new VcsException(e));
      } catch (VcsException e) {
        exceptions.add(e);
      }
    }

    // push if needed
    if (myNextCommitIsPushed && exceptions.isEmpty()) {
      final Set<VirtualFile> preselectedFiles = repositoriesMap.keySet();
      HgRepositoryManager repositoryManager = HgUtil.getRepositoryManager(myProject);
      final List<HgRepository> preselectedRepositories = HgActionUtil.collectRepositoriesFromFiles(repositoryManager, preselectedFiles);
      UIUtil.invokeLaterIfNeeded(new Runnable() {
        public void run() {
          new VcsPushDialog(myProject, preselectedRepositories).show();
        }
      });
    }

    return exceptions;
  }

  private boolean isMergeCommit(VirtualFile repo) {
    return new HgWorkingCopyRevisionsCommand(myProject).parents(repo).size() > 1;
  }

  private Set<HgFile> getChangedFilesNotInCommit(VirtualFile repo, Set<HgFile> selectedFiles) {
    List<HgRevisionNumber> parents = new HgWorkingCopyRevisionsCommand(myProject).parents(repo);

    HgStatusCommand statusCommand = new HgStatusCommand.Builder(true).unknown(false).ignored(false).baseRevision(parents.get(0)).build(myProject);
    Set<HgChange> allChangedFilesInRepo = statusCommand.execute(repo);

    Set<HgFile> filesNotIncluded = new HashSet<HgFile>();

    for (HgChange change : allChangedFilesInRepo) {
      HgFile beforeFile = change.beforeFile();
      HgFile afterFile = change.afterFile();
      if (!selectedFiles.contains(beforeFile)) {
        filesNotIncluded.add(beforeFile);
      } else if (!selectedFiles.contains(afterFile)) {
        filesNotIncluded.add(afterFile);
      }
    }
    return filesNotIncluded;
  }

  private boolean mayCommitEverything(final String filesNotIncludedString) {
    final int[] choice = new int[1];
    Runnable runnable = new Runnable() {
      public void run() {
        choice[0] = Messages.showOkCancelDialog(
          myProject,
          HgVcsMessages.message("hg4idea.commit.partial.merge.message", filesNotIncludedString),
          HgVcsMessages.message("hg4idea.commit.partial.merge.title"),
          null
        );
      }
    };
    if (!ApplicationManager.getApplication().isDispatchThread()) {
      ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.defaultModalityState());
    } else {
      runnable.run();
    }
    return choice[0] == Messages.OK;
  }

  public List<VcsException> commit(List<Change> changes, String preparedComment) {
    return commit(changes, preparedComment, FunctionUtil.nullConstant(), null);
  }

  public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) {
    final List<HgFile> filesWithRoots = new ArrayList<HgFile>();
    for (FilePath filePath : files) {
      VirtualFile vcsRoot = VcsUtil.getVcsRootFor(myProject, filePath);
      if (vcsRoot == null) {
        continue;
      }
      filesWithRoots.add(new HgFile(vcsRoot, filePath));
    }
    new Task.Backgroundable(myProject, "Removing files...") {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        HgRemoveCommand command = new HgRemoveCommand(myProject);
        command.execute(filesWithRoots);
      }
    }.queue();
    return null;
  }

  public List<VcsException> scheduleUnversionedFilesForAddition(final List<VirtualFile> files) {
    new HgAddCommand(myProject).addWithProgress(files);
    return null;
  }

  public boolean keepChangeListAfterCommit(ChangeList changeList) {
    return false;
  }

  @Override
  public boolean isRefreshAfterCommitNeeded() {
    return false;
  }

  @NotNull
  private Map<VirtualFile, Set<HgFile>> getFilesByRepository(List<Change> changes) {
    Map<VirtualFile, Set<HgFile>> result = new HashMap<VirtualFile, Set<HgFile>>();
    for (Change change : changes) {
      ContentRevision afterRevision = change.getAfterRevision();
      ContentRevision beforeRevision = change.getBeforeRevision();

      if (afterRevision != null) {
        addFile(result, afterRevision.getFile());
      }
      if (beforeRevision != null) {
        addFile(result, beforeRevision.getFile());
      }
    }
    return result;
  }

  private void addFile(Map<VirtualFile, Set<HgFile>> result, FilePath filePath) {
    if (filePath == null) {
      return;
    }

    VirtualFile repo = VcsUtil.getVcsRootFor(myProject, filePath);
    if (repo == null || filePath.isDirectory()) {
      return;
    }

    Set<HgFile> hgFiles = result.get(repo);
    if (hgFiles == null) {
      hgFiles = new HashSet<HgFile>();
      result.put(repo, hgFiles);
    }

    hgFiles.add(new HgFile(repo, filePath));
  }

  public void setNextCommitIsPushed() {
    myNextCommitIsPushed = true;
  }

  /**
   * Commit options for hg
   */
  private class HgCommitAdditionalComponent extends DvcsCommitAdditionalComponent {

    public HgCommitAdditionalComponent(@NotNull Project project, @NotNull CheckinProjectPanel panel) {
      super(project, panel);
      HgVcs myVcs = HgVcs.getInstance(myProject);
      myAmend.setEnabled(myVcs != null && myVcs.getVersion().isAmendSupported());
    }

    @Override
    public void refresh() {
      super.refresh();
      myNextCommitAmend = false;
    }

    @Override
    public void saveState() {
      myNextCommitAmend = myAmend.isSelected();
    }

    @Override
    public void restoreState() {
      myNextCommitAmend = false;
    }

    @NotNull
    @Override
    protected Set<VirtualFile> getVcsRoots(@NotNull Collection<FilePath> filePaths) {
      return HgUtil.hgRoots(myProject, filePaths);
    }

    @Nullable
    @Override
    protected String getLastCommitMessage(@NotNull VirtualFile repo) throws VcsException {
      HgCommandExecutor commandExecutor = new HgCommandExecutor(myProject);
      List<String> args = new ArrayList<String>();
      args.add("-r");
      args.add(".");
      args.add("--template");
      args.add("{desc}");
      HgCommandResult result = commandExecutor.executeInCurrentThread(repo, "log", args);
      return result == null ? "" : result.getRawOutput();
    }
  }
}