Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 93056b574a3e6da7825675fac1ea636325980c5b (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
/*******************************************************************************
 * Copyright (C) 2010, 2013 Dariusz Luksza <dariusz@luksza.org> and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Dariusz Luksza <dariusz@luksza.org> - initial API and implementation
 *     Laurent Goubet <laurent.goubet@obeo.fr> - Logical Model enhancements
 *     Gunnar Wagenknecht <gunnar@wagenknecht.org> - Logical Model enhancements
 *******************************************************************************/
package org.eclipse.egit.ui.internal.synchronize;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.compare.CompareNavigator;
import org.eclipse.compare.ITypedElement;
import org.eclipse.compare.ResourceNode;
import org.eclipse.compare.structuremergeviewer.ICompareInput;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IEncodedStorage;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.mapping.ModelProvider;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.egit.core.AdapterUtils;
import org.eclipse.egit.core.internal.storage.WorkspaceFileRevision;
import org.eclipse.egit.core.project.GitProjectData;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.core.synchronize.GitResourceVariantTreeSubscriber;
import org.eclipse.egit.core.synchronize.GitSubscriberMergeContext;
import org.eclipse.egit.core.synchronize.GitSubscriberResourceMappingContext;
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeData;
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataSet;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.egit.ui.internal.FileRevisionTypedElement;
import org.eclipse.egit.ui.internal.GitCompareFileRevisionEditorInput;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.synchronize.model.GitModelBlob;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.history.IFileRevision;
import org.eclipse.team.core.mapping.ISynchronizationContext;
import org.eclipse.team.core.mapping.ISynchronizationScopeManager;
import org.eclipse.team.core.mapping.provider.MergeContext;
import org.eclipse.team.core.mapping.provider.SynchronizationScopeManager;
import org.eclipse.team.core.subscribers.Subscriber;
import org.eclipse.team.core.subscribers.SubscriberMergeContext;
import org.eclipse.team.internal.ui.mapping.ResourceDiffCompareInput;
import org.eclipse.team.ui.TeamUI;
import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
import org.eclipse.team.ui.synchronize.ModelSynchronizeParticipant;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;

/**
 * Git model synchronization participant
 */
public class GitModelSynchronizeParticipant extends ModelSynchronizeParticipant {

	/**
	 * Key value for obtaining {@link GitSynchronizeDataSet} from {@link ISynchronizePageConfiguration}
	 */
	public static final String SYNCHRONIZATION_DATA = "GIT_SYNCHRONIZE_DATA_SET"; //$NON-NLS-1$

	/**
	 * Id of model compare participant
	 */
	public static final String ID = "org.eclipse.egit.ui.modelCompareParticipant"; //$NON-NLS-1$

	/**
	 * Id of model synchronization participant
	 */
	public static final String VIEWER_ID = "org.eclipse.egit.ui.compareSynchronization"; //$NON-NLS-1$

	private static final String P_NAVIGATOR = "org.eclipse.team.ui.P_NAVIGATOR"; //$NON-NLS-1$

	private static final String WORKSPACE_MODEL_PROVIDER_ID = "org.eclipse.core.resources.modelProvider"; //$NON-NLS-1$

	private static final String DATA_NODE_KEY = "gitSynchronizeData"; //$NON-NLS-1$

	private static final String INCLUDED_PATHS_NODE_KEY = "includedPaths"; //$NON-NLS-1$

	private static final String INCLUDED_PATH_KEY = "path"; //$NON-NLS-1$

	private static final String CONTAINER_PATH_KEY = "container"; //$NON-NLS-1$

	private static final String SRC_REV_KEY = "srcRev"; //$NON-NLS-1$

	private static final String DST_REV_KEY = "dstRev"; //$NON-NLS-1$

	private static final String INCLUDE_LOCAL_KEY = "inludeLocal"; //$NON-NLS-1$

	private static final String FORCE_FETCH_KEY = "forceFetch"; //$NON-NLS-1$


	private GitSynchronizeDataSet gsds;

	/**
	 * DO NOT USE. This constructor is preserved for dynamic initialization when
	 * synchronization context is restored
	 */
	public GitModelSynchronizeParticipant() {
	}

	/**
	 * Creates {@link GitModelSynchronizeParticipant} for given context
	 *
	 * @param context
	 */
	public GitModelSynchronizeParticipant(GitSubscriberMergeContext context) {
		super(context);
		gsds = context.getSyncData();

		try {
			setInitializationData(TeamUI.getSynchronizeManager()
					.getParticipantDescriptor(ID));
		} catch (CoreException e) {
			Activator.logError(e.getMessage(), e);
		}

		setSecondaryId(Long.toString(System.currentTimeMillis()));
	}

	protected void initializeConfiguration(
			final ISynchronizePageConfiguration configuration) {
		configuration.setProperty(ISynchronizePageConfiguration.P_VIEWER_ID,
				VIEWER_ID);
		String modelProvider = WORKSPACE_MODEL_PROVIDER_ID;
		final IPreferenceStore preferenceStore = Activator.getDefault()
				.getPreferenceStore();
		if (!gsds.containsFolderLevelSynchronizationRequest()) {
			if (preferenceStore
					.getBoolean(UIPreferences.SYNC_VIEW_ALWAYS_SHOW_CHANGESET_MODEL)) {
				modelProvider = GitChangeSetModelProvider.ID;
			} else {
				String lastSelectedModel = preferenceStore.getString(UIPreferences.SYNC_VIEW_LAST_SELECTED_MODEL);
				if (!"".equals(lastSelectedModel)) //$NON-NLS-1$
					modelProvider = lastSelectedModel;
			}
		}

		configuration.setProperty(
				ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER,
				modelProvider);

		configuration.setProperty(SYNCHRONIZATION_DATA, gsds);

		super.initializeConfiguration(configuration);

		configuration.addActionContribution(new GitActionContributor());

		configuration.addPropertyChangeListener(new IPropertyChangeListener() {

			public void propertyChange(PropertyChangeEvent event) {
				String property = event.getProperty();
				if (property.equals(
						ModelSynchronizeParticipant.P_VISIBLE_MODEL_PROVIDER)) {
					String newValue = (String) event.getNewValue();
					preferenceStore.setValue(
							UIPreferences.SYNC_VIEW_LAST_SELECTED_MODEL,
							newValue);
				} else if (property.equals(P_NAVIGATOR)) {
					Object oldNavigator = configuration
							.getProperty(P_NAVIGATOR);
					if (!(oldNavigator instanceof GitTreeCompareNavigator))
						configuration.setProperty(P_NAVIGATOR,
								new GitTreeCompareNavigator(
										(CompareNavigator) oldNavigator));
				}
			}
		});
	}

	@Override
	public ModelProvider[] getEnabledModelProviders() {
		ModelProvider[] avaliableProviders = super.getEnabledModelProviders();

		for (ModelProvider provider : avaliableProviders)
			if (provider.getId().equals(GitChangeSetModelProvider.ID))
				return avaliableProviders;

		int capacity = avaliableProviders.length + 1;
		ArrayList<ModelProvider> providers = new ArrayList<ModelProvider>(
				capacity);
		providers.add(GitChangeSetModelProvider.getProvider());

		return providers.toArray(new ModelProvider[providers.size()]);
	}

	@Override
	public boolean hasCompareInputFor(Object object) {
		if (object instanceof GitModelBlob || object instanceof IFile)
			return true;

		// in Java Workspace model Java source files are passed as type
		// CompilationUnit which can be adapted to IResource
		IResource res = AdapterUtils.adapt(object, IResource.class);
		if (res != null && res.getType() == IResource.FILE)
			return true;

		// fallback to super ISynchronizationCompareAdapter
		return super.hasCompareInputFor(object);
	}

	@Override
	public ICompareInput asCompareInput(Object object) {
		final ICompareInput input = super.asCompareInput(object);
		final ISynchronizationContext ctx = getContext();

		if (input instanceof ResourceDiffCompareInput && ctx instanceof SubscriberMergeContext) {
			// Team only considers local resources as "left"
			// We'll use the cached data instead as left could be remote
			final IResource resource = ((ResourceNode) input.getLeft())
					.getResource();
			final Subscriber subscriber = ((SubscriberMergeContext)ctx).getSubscriber();

			if (resource instanceof IFile
					&& subscriber instanceof GitResourceVariantTreeSubscriber) {
				try {
					final IFileRevision revision = ((GitResourceVariantTreeSubscriber) subscriber)
							.getSourceFileRevision((IFile) resource);
					if (revision == null) {
						final ITypedElement newSource = new GitCompareFileRevisionEditorInput.EmptyTypedElement(
								resource.getName());
						((ResourceDiffCompareInput) input).setLeft(newSource);
					} else if (!(revision instanceof WorkspaceFileRevision)) {
						final ITypedElement newSource = new FileRevisionTypedElement(
								revision, getLocalEncoding(resource));
						((ResourceDiffCompareInput) input).setLeft(newSource);
					}
				} catch (TeamException e) {
					// Keep the input from super as-is
					String error = NLS
							.bind(UIText.GitModelSynchronizeParticipant_noCachedSourceVariant,
									resource.getName());
					Activator.logError(error, e);
				}
			}
		}

		return input;
	}

	private static String getLocalEncoding(IResource resource) {
		if (resource instanceof IEncodedStorage) {
			IEncodedStorage es = (IEncodedStorage) resource;
			try {
				return es.getCharset();
			} catch (CoreException e) {
				Activator.logError(e.getMessage(), e);
			}
		}
		return null;
	}

	@Override
	public void run(final IWorkbenchPart part) {
		boolean launchFetch = Activator.getDefault().getPreferenceStore()
				.getBoolean(UIPreferences.SYNC_VIEW_FETCH_BEFORE_LAUNCH);
		if (launchFetch || gsds.forceFetch()) {
			Job fetchJob = new SynchronizeFetchJob(gsds);
			fetchJob.setUser(true);
			fetchJob.addJobChangeListener(new JobChangeAdapter() {
				@Override
				public void done(IJobChangeEvent event) {
					GitModelSynchronizeParticipant.super.run(part);
				}
			});

			fetchJob.schedule();
		} else
			super.run(part);
	}

	@Override
	public void saveState(IMemento memento) {
		super.saveState(memento);
		for (GitSynchronizeData gsd : gsds) {
			Repository repo = gsd.getRepository();
			RepositoryMapping mapping = RepositoryMapping.findRepositoryMapping(repo);
			if (mapping != null) {
				IMemento child = memento.createChild(DATA_NODE_KEY);
				child.putString(CONTAINER_PATH_KEY, getPathForContainer(mapping.getContainer()));
				child.putString(SRC_REV_KEY, gsd.getSrcRev());
				child.putString(DST_REV_KEY, gsd.getDstRev());
				child.putBoolean(INCLUDE_LOCAL_KEY, gsd.shouldIncludeLocal());
				Set<IContainer> includedPaths = gsd.getIncludedPaths();
				if (includedPaths != null && !includedPaths.isEmpty()) {
					IMemento paths = child.createChild(INCLUDED_PATHS_NODE_KEY);
					for (IContainer container : includedPaths) {
						String path = getPathForContainer(container);
						paths.createChild(INCLUDED_PATH_KEY).putString(
								INCLUDED_PATH_KEY, path);
					}
				}
			}
		}
		memento.putBoolean(FORCE_FETCH_KEY, gsds.forceFetch());
	}

	@Override
	public void init(String secondaryId, IMemento memento)
			throws PartInitException {
		try {
			boolean forceFetchPref = Activator.getDefault().getPreferenceStore()
					.getBoolean(UIPreferences.SYNC_VIEW_FETCH_BEFORE_LAUNCH);
			boolean forceFetch = getBoolean(memento.getBoolean(FORCE_FETCH_KEY), forceFetchPref);
			gsds = new GitSynchronizeDataSet(forceFetch);
			IMemento[] children = memento.getChildren(DATA_NODE_KEY);
			if (children != null)
				restoreSynchronizationData(children);
		} finally {
			super.init(secondaryId, memento);
		}
	}

	@Override
	protected MergeContext restoreContext(ISynchronizationScopeManager manager)
			throws CoreException {
		GitResourceVariantTreeSubscriber subscriber = new GitResourceVariantTreeSubscriber(
				gsds);
		subscriber.init(new NullProgressMonitor());
		return new GitSubscriberMergeContext(subscriber, manager, gsds);
	}

	@Override
	protected ISynchronizationScopeManager createScopeManager(
			ResourceMapping[] mappings) {
		GitResourceVariantTreeSubscriber subscriber = new GitResourceVariantTreeSubscriber(
				gsds);
		subscriber.init(new NullProgressMonitor());
		GitSubscriberResourceMappingContext context = new GitSubscriberResourceMappingContext(
				subscriber, gsds);
		return new SynchronizationScopeManager(
				UIText.GitModelSynchronizeParticipant_initialScopeName,
				mappings, context, true);
	}

	private void restoreSynchronizationData(IMemento[] children) {
		for (IMemento child : children) {
			String containerPath = child.getString(CONTAINER_PATH_KEY);
			Repository repo = getRepositoryForPath(containerPath);
			if (repo == null)
				continue;
			String srcRev = child.getString(SRC_REV_KEY);
			String dstRev = child.getString(DST_REV_KEY);
			boolean includeLocal = getBoolean(
					child.getBoolean(INCLUDE_LOCAL_KEY), true);
			Set<IContainer> includedPaths = getIncludedPaths(child);
			try {
				GitSynchronizeData data = new GitSynchronizeData(repo, srcRev,
						dstRev, includeLocal);
				if (includedPaths != null)
					data.setIncludedPaths(includedPaths);
				gsds.add(data);
			} catch (IOException e) {
				Activator.logError(e.getMessage(), e);
				continue;
			}
		}
	}

	private Repository getRepositoryForPath(String containerPath) {
		IPath path = Path.fromPortableString(containerPath);
		IContainer mappedContainer = ResourcesPlugin.getWorkspace().getRoot()
				.getContainerForLocation(path);
		GitProjectData projectData = GitProjectData.get((IProject) mappedContainer);
		RepositoryMapping mapping = projectData.getRepositoryMapping(mappedContainer);
		if (mapping != null)
			return mapping.getRepository();
		return null;
	}

	private boolean getBoolean(Boolean value, boolean defaultValue) {
		return value != null ? value.booleanValue() : defaultValue;
	}

	private String getPathForContainer(IContainer container) {
		return container.getLocation().toPortableString();
	}

	private Set<IContainer> getIncludedPaths(IMemento memento) {
		IMemento child = memento.getChild(INCLUDED_PATHS_NODE_KEY);
		Set<IContainer> result = new HashSet<IContainer>();
		if (child != null) {
			IMemento[] pathNode = child.getChildren(INCLUDED_PATH_KEY);
			if (pathNode != null) {
				for (IMemento path : pathNode) {
					String includedPath = path.getString(INCLUDED_PATH_KEY);
					IContainer container = ResourcesPlugin.getWorkspace().getRoot()
							.getContainerForLocation(new Path(includedPath));
					result.add(container);
				}
				return result;
			}
		}
		return null;
	}

}

Back to the top