Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 7eadaad46decacb5a3e0c8962eed4d8a53b76e9e (plain) (blame)
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*******************************************************************************
 * Copyright (c) 2005, 2009 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.ltk.ui.refactoring.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.team.core.diff.IDiff;
import org.eclipse.team.core.diff.IThreeWayDiff;
import org.eclipse.team.core.diff.ITwoWayDiff;
import org.eclipse.team.core.history.IFileRevision;
import org.eclipse.team.core.mapping.IMergeContext;
import org.eclipse.team.core.mapping.IMergeStatus;
import org.eclipse.team.core.mapping.IResourceDiff;
import org.eclipse.team.core.mapping.ResourceMappingMerger;
import org.eclipse.team.core.mapping.provider.MergeStatus;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.mapping.ModelProvider;
import org.eclipse.core.resources.mapping.ResourceMapping;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;

import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
import org.eclipse.ltk.internal.core.refactoring.history.RefactoringHistoryImplementation;
import org.eclipse.ltk.internal.core.refactoring.history.RefactoringHistoryService;
import org.eclipse.ltk.internal.ui.refactoring.RefactoringUIMessages;
import org.eclipse.ltk.internal.ui.refactoring.RefactoringUIPlugin;
import org.eclipse.ltk.internal.ui.refactoring.model.RefactoringHistoryMergeWizard;
import org.eclipse.ltk.ui.refactoring.history.RefactoringHistoryControlConfiguration;

/**
 * Partial implementation of a refactoring-aware resource mapping merger.
 * <p>
 * This class provides support to determine pending refactorings during model
 * merging and model update, and displays a refactoring wizard to apply the
 * refactorings to the local workspace.
 * </p>
 * <p>
 * Note: this class is designed to be extended by clients. Programming language
 * implementers which need a refactoring-aware resource mapping merger to
 * associated with their model provider may extend this class to implement
 * language-specific project dependency rules.
 * </p>
 *
 * @see org.eclipse.team.core.mapping.IResourceMappingMerger
 *
 * @since 3.2
 */
public abstract class AbstractResourceMappingMerger extends ResourceMappingMerger {

	/** Refactoring history model merge configuration */
	private static final class RefactoringHistoryModelMergeConfiguration extends RefactoringHistoryControlConfiguration {

		/**
		 * Creates a new refactoring history model merge configuration.
		 *
		 * @param project
		 *            the project, or <code>null</code>
		 */
		public RefactoringHistoryModelMergeConfiguration(final IProject project) {
			super(project, false, false);
		}

		@Override
		public String getProjectPattern() {
			return RefactoringUIMessages.RefactoringModelMerger_project_pattern;
		}

		@Override
		public String getWorkspaceCaption() {
			return RefactoringUIMessages.RefactoringModelMerger_workspace_caption;
		}
	}

	/** The refactoring history model merge wizard */
	private static final class RefactoringHistoryModelMergeWizard extends RefactoringHistoryMergeWizard {

		/**
		 * Creates a new refactoring history model merge wizard.
		 */
		public RefactoringHistoryModelMergeWizard() {
			super(RefactoringUIMessages.RefactoringWizard_refactoring, RefactoringUIMessages.AbstractRefactoringModelMerger_wizard_title, RefactoringUIMessages.AbstractRefactoringModelMerger_wizard_description);
		}
	}

	/**
	 * Returns the shell of the active workbench window.
	 *
	 * @return the active shell
	 */
	private static Shell getActiveShell() {
		final IWorkbench workbench= PlatformUI.getWorkbench();
		if (workbench != null) {
			final IWorkbenchWindow window= workbench.getActiveWorkbenchWindow();
			if (window != null)
				return window.getShell();
		}
		return null;
	}

	/**
	 * Returns the projects affected by the specified refactoring history.
	 *
	 * @param history
	 *            the refactoring history
	 * @return the affected projects, or <code>null</code> if the entire
	 *         workspace is affected
	 */
	private static IProject[] getAffectedProjects(final RefactoringHistory history) {
		final Set<IProject> set= new HashSet<>();
		final IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		for (RefactoringDescriptorProxy proxy : history.getDescriptors()) {
			final String name= proxy.getProject();
			if (name != null && !"".equals(name)) //$NON-NLS-1$
				set.add(root.getProject(name));
			else
				return null;
		}
		final IProject[] projects= new IProject[set.size()];
		set.toArray(projects);
		return projects;
	}

	/**
	 * Return a shell that can be used by the operation to display dialogs, etc.
	 *
	 * @return a shell
	 */
	private static Shell getDialogShell() {
		final Shell[] shell= new Shell[] { null};
		Display.getDefault().syncExec(new Runnable() {

			@Override
			public final void run() {
				shell[0]= getActiveShell();
			}
		});
		return shell[0];
	}

	/** The model provider */
	private final ModelProvider fModelProvider;

	/**
	 * Creates a new abstract refactoring model merger.
	 *
	 * @param provider
	 *            the model provider
	 */
	protected AbstractResourceMappingMerger(final ModelProvider provider) {
		Assert.isNotNull(provider);
		fModelProvider= provider;
	}

	/**
	 * Hook method which is called before the actual merge process happens.
	 * <p>
	 * Subclasses may extend this method to perform any special processing. The
	 * default implementation checks whether there are any pending refactorings
	 * in the merge context and displays a refactoring wizard to let the user
	 * perform the pending refactorings before merge.
	 * </p>
	 * <p>
	 * Returning a status of severity {@link IStatus#ERROR} will terminate the
	 * merge process.
	 * </p>
	 *
	 * @param context
	 *            the merge context
	 * @param monitor
	 *            the progress monitor to use
	 * @return a status describing the outcome of the operation
	 */
	protected IStatus aboutToPerformMerge(final IMergeContext context, final IProgressMonitor monitor) {
		Assert.isNotNull(context);
		Assert.isNotNull(monitor);
		try {
			monitor.beginTask(RefactoringUIMessages.RefactoringModelMerger_merge_message, 100);
			final IDiff[] diffs= getDiffs(context);
			final RefactoringHistory history= getRefactoringHistory(diffs, monitor);
			if (history != null && !history.isEmpty()) {
				boolean execute= true;
				final IProject[] projects= getAffectedProjects(history);
				if (projects != null) {
					final IProject[] dependencies= getDependencies(projects);
					if (dependencies.length == 0)
						execute= false;
				}
				if (execute) {
					final Shell shell= getDialogShell();
					shell.getDisplay().syncExec(new Runnable() {

						@Override
						public final void run() {
							if (MessageDialog.openQuestion(shell, RefactoringUIMessages.RefactoringWizard_refactoring, RefactoringUIMessages.AbstractRefactoringModelMerger_accept_question)) {
								final RefactoringHistoryMergeWizard wizard= new RefactoringHistoryModelMergeWizard();
								int result= Window.OK;
								try {
									wizard.setConfiguration(new RefactoringHistoryModelMergeConfiguration((projects != null && projects.length == 1) ? projects[0] : null));
									wizard.setInput(history);
									result= new WizardDialog(shell, wizard).open();
								} finally {
									if (result != Window.CANCEL)
										wizard.resolveConflicts(context);
								}
							}
						}
					});
				}
			}
		} finally {
			monitor.done();
		}
		return Status.OK_STATUS;
	}

	/**
	 * Creates a merge status.
	 *
	 * @param context
	 *            the merge context
	 * @param status
	 *            the status
	 * @return the resulting merge status
	 */
	private IStatus createMergeStatus(final IMergeContext context, final IStatus status) {
		if (status.getCode() == IMergeStatus.CONFLICTS)
			return new MergeStatus(status.getPlugin(), status.getMessage(), context.getScope().getMappings(fModelProvider.getDescriptor().getId()));
		return status;
	}

	/**
	 * Returns the dependent projects of the projects associated with the
	 * incoming refactorings.
	 * <p>
	 * Subclasses must implement this method to return the dependent projects
	 * according to the semantics of the associated programming language. The
	 * result of this method is used to decide whether the resource mapping
	 * merger should execute the incoming refactorings in order to fix up
	 * references in dependent projects.
	 * </p>
	 *
	 * @param projects
	 *            the projects associated with the incoming refactorings in the
	 *            synchronization scope.
	 * @return the dependent projects, or an empty array
	 */
	protected abstract IProject[] getDependencies(IProject[] projects);

	/**
	 * Returns the diffs from the merge context.
	 *
	 * @param context
	 *            the merge context
	 * @return the diffs, or an empty array
	 */
	private IDiff[] getDiffs(final IMergeContext context) {
		final ResourceMapping[] mappings= context.getScope().getMappings(fModelProvider.getDescriptor().getId());
		final Set<IDiff> set= new HashSet<>();
		for (int index= 0; index < mappings.length; index++) {
			final IDiff[] diffs= context.getDiffTree().getDiffs(context.getScope().getTraversals(mappings[index]));
			set.addAll(Arrays.asList(diffs));
		}
		return set.toArray(new IDiff[set.size()]);
	}

	@Override
	protected final ModelProvider getModelProvider() {
		return fModelProvider;
	}

	/**
	 * Returns the incoming refactoring history from the diffs.
	 *
	 * @param diffs
	 *            the diffs
	 * @param monitor
	 *            the progress monitor to use
	 * @return the incoming refactoring history
	 */
	private RefactoringHistory getRefactoringHistory(final IDiff[] diffs, final IProgressMonitor monitor) {
		final Set<RefactoringDescriptor> result= new HashSet<>();
		try {
			monitor.beginTask(RefactoringUIMessages.RefactoringModelMerger_retrieving_refactorings, diffs.length * 2);
			for (IDiff diff : diffs) {
				if (diff instanceof IThreeWayDiff) {
					final IThreeWayDiff threeWay= (IThreeWayDiff) diff;
					final Set<RefactoringDescriptor> localDescriptors= new HashSet<>();
					final Set<RefactoringDescriptor> remoteDescriptors= new HashSet<>();
					final ITwoWayDiff localDiff= threeWay.getLocalChange();
					if (localDiff instanceof IResourceDiff && localDiff.getKind() != IDiff.NO_CHANGE) {
						final IResourceDiff resourceDiff= (IResourceDiff) localDiff;
						final IFileRevision revision= resourceDiff.getAfterState();
						if (revision != null) {
							final String name= revision.getName();
							if (name.equalsIgnoreCase(RefactoringHistoryService.NAME_HISTORY_FILE))
								getRefactoringDescriptors(revision, localDescriptors, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						}
					}
					final ITwoWayDiff remoteDiff= threeWay.getLocalChange();
					if (remoteDiff instanceof IResourceDiff && remoteDiff.getKind() != IDiff.NO_CHANGE) {
						final IResourceDiff resourceDiff= (IResourceDiff) remoteDiff;
						final IFileRevision revision= resourceDiff.getAfterState();
						if (revision != null) {
							final String name= revision.getName();
							if (name.equalsIgnoreCase(RefactoringHistoryService.NAME_HISTORY_FILE))
								getRefactoringDescriptors(revision, remoteDescriptors, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
						}
					}
					remoteDescriptors.removeAll(localDescriptors);
					result.addAll(remoteDescriptors);
				}
			}
		} finally {
			monitor.done();
		}
		return new RefactoringHistoryImplementation(result.toArray(new RefactoringDescriptorProxy[result.size()]));
	}

	/**
	 * Retrieves the refactoring descriptors contained in the specified file
	 * revision.
	 *
	 * @param revision
	 *            the file revision
	 * @param descriptors
	 *            the refactoring descriptor set to populate
	 * @param monitor
	 *            the progress monitor to use
	 */
	static final void getRefactoringDescriptors(final IFileRevision revision, final Set<RefactoringDescriptor> descriptors, final IProgressMonitor monitor) {
		try {
			monitor.beginTask(RefactoringUIMessages.RefactoringModelMerger_retrieving_refactorings, 1);
			IStorage storage= null;
			try {
				storage= revision.getStorage(new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
			} catch (CoreException exception) {
				RefactoringUIPlugin.log(exception);
			}
			if (storage != null) {
				InputStream stream= null;
				try {
					stream= storage.getContents();
					final RefactoringHistory history= RefactoringHistoryService.getInstance().readRefactoringHistory(stream, RefactoringDescriptor.MULTI_CHANGE);
					for (RefactoringDescriptorProxy proxy : history.getDescriptors()) {
						descriptors.add(proxy.requestDescriptor(null));
					}
				} catch (CoreException exception) {
					RefactoringUIPlugin.log(exception);
				} finally {
					if (stream != null) {
						try {
							stream.close();
						} catch (IOException exception) {
							// Do nothing
						}
					}
				}
			}
		} finally {
			monitor.done();
		}
	}

	@Override
	public IStatus merge(final IMergeContext context, IProgressMonitor monitor) throws CoreException {
		Assert.isNotNull(context);
		IStatus status= Status.OK_STATUS;
		if (monitor == null)
			monitor= new NullProgressMonitor();
		try {
			monitor.beginTask(RefactoringUIMessages.RefactoringModelMerger_merge_message, 200);
//			status= aboutToPerformMerge(context, new SubProgressMonitor(monitor, 75));
			if (status.getSeverity() != IStatus.ERROR) {
				final IDiff[] diffs= getDiffs(context);
				status= createMergeStatus(context, context.merge(diffs, false, new SubProgressMonitor(monitor, 100)));
				final int code= status.getCode();
				if (status.getSeverity() != IStatus.ERROR && code != IMergeStatus.CONFLICTS && code != IMergeStatus.INTERNAL_ERROR)
					status= mergePerformed(context, new SubProgressMonitor(monitor, 25));
			}
		} finally {
			monitor.done();
		}
		return status;
	}

	/**
	 * Hook method which is called after the actual merge process happened. This
	 * method is only called if {@link #merge(IMergeContext, IProgressMonitor)}
	 * returns a status with severity less than {@link IStatus#ERROR} and a
	 * status code unequal to {@link IMergeStatus#CONFLICTS} or
	 * {@link IMergeStatus#INTERNAL_ERROR}.
	 * <p>
	 * Subclasses may extend this method to perform any special processing. The
	 * default implementation does nothing.
	 * </p>
	 *
	 * @param context
	 *            the merge context
	 * @param monitor
	 *            the progress monitor to use
	 * @return a status describing the outcome of the operation
	 */
	protected IStatus mergePerformed(final IMergeContext context, final IProgressMonitor monitor) {
		Assert.isNotNull(context);
		Assert.isNotNull(monitor);
		try {
			monitor.beginTask(RefactoringUIMessages.RefactoringModelMerger_merge_message, 1);
			return Status.OK_STATUS;
		} finally {
			monitor.done();
		}
	}
}

Back to the top