Skip to main content
summaryrefslogtreecommitdiffstats
blob: 3c227e6742115ed96dab00754e36e531b67953b6 (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
/*******************************************************************************
 * Copyright (C) 2013, 2014 Obeo 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
 *******************************************************************************/
package org.eclipse.emf.compare.ide.ui.tests.egit.fixture;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.mapping.IModelProviderDescriptor;
import org.eclipse.core.resources.mapping.ModelProvider;
import org.eclipse.core.resources.mapping.RemoteResourceMappingContext;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.resources.mapping.ResourceMappingContext;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.egit.core.Activator;
import org.eclipse.egit.core.op.BranchOperation;
import org.eclipse.egit.core.op.ConnectProviderOperation;
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.emf.compare.ide.ui.tests.workspace.TestProject;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoFilepatternException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.team.core.subscribers.Subscriber;
import org.eclipse.team.core.subscribers.SubscriberScopeManager;

/**
 * This class is largely inspired from org.eclipse.egit.core.test.TestRepository. It has been copied here in
 * order to be usable from our build without dependencies towards egit.core.tests.
 */
@SuppressWarnings({"nls", "restriction" })
public class GitTestRepository {
	Repository repository;

	String workdirPrefix;

	/**
	 * Creates a new test repository.
	 * 
	 * @param gitDir
	 *            The ".git" file we'll use to create a repository.
	 * @throws IOException
	 *             Thrown if we cannot write at the given location.
	 */
	public GitTestRepository(File gitDir) throws IOException {
		repository = Activator.getDefault().getRepositoryCache().lookupRepository(gitDir);
		repository.create();

		try {
			workdirPrefix = repository.getWorkTree().getCanonicalPath();
		} catch (IOException err) {
			workdirPrefix = repository.getWorkTree().getAbsolutePath();
		}
		workdirPrefix = workdirPrefix.replace('\\', '/');
		if (!workdirPrefix.endsWith("/")) {
			workdirPrefix += "/";
		}
	}

	/**
	 * Track, add to index and finally commit the given files.
	 * 
	 * @param testProject
	 *            The project within which this file is located.
	 * @param commitMessage
	 *            Message with which to commit this file.
	 * @param files
	 *            The files to add and commit.
	 * @return The RevCommit corresponding to this operation.
	 */
	public RevCommit addAndCommit(TestProject testProject, String commitMessage, File... files)
			throws Exception {
		track(files);
		addToIndex(testProject, files);
		return commit(commitMessage);
	}

	/**
	 * Adds The given files to version control.
	 * 
	 * @param files
	 *            The files to add.
	 */
	public void track(File... files) throws IOException, NoFilepatternException, GitAPIException {
		for (File file : files) {
			String repoPath = getRepoRelativePath(new Path(file.getPath()).toString());
			new Git(repository).add().addFilepattern(repoPath).call();
		}
	}

	/**
	 * Adds the given files to the index.
	 * 
	 * @param testProject
	 *            Project that contains these files.
	 * @param files
	 *            Files to add to the index.
	 */
	public void addToIndex(TestProject testProject, File... files) throws Exception {
		for (File file : files) {
			addToIndex(testProject.getIFile(testProject.getProject(), file));
		}
	}

	/**
	 * Adds the given resources to the index
	 * 
	 * @param resources
	 *            Resources to add to the index.
	 */
	public void addToIndex(IResource... resources) throws CoreException, IOException, NoFilepatternException,
			GitAPIException {
		for (IResource resource : resources) {
			String repoPath = getRepoRelativePath(resource.getLocation().toOSString());
			new Git(repository).add().addFilepattern(repoPath).call();
		}
	}

	/**
	 * Commits the current index.
	 * 
	 * @param message
	 *            commit message
	 * @return commit object
	 */
	public RevCommit commit(String message) throws Exception {
		Git git = new Git(repository);
		CommitCommand commitCommand = git.commit();
		commitCommand.setAuthor("J. Git", "j.git@egit.org");
		commitCommand.setCommitter(commitCommand.getAuthor());
		commitCommand.setMessage(message);
		return commitCommand.call();
	}

	/**
	 * Connect a project to this repository.
	 * 
	 * @param project
	 *            The project to connect
	 */
	public void connect(IProject project) throws CoreException {
		ConnectProviderOperation op = new ConnectProviderOperation(project, repository.getDirectory());
		op.execute(null);
	}

	/**
	 * Creates a new branch.
	 * 
	 * @param refName
	 *            Starting point for the new branch.
	 * @param newRefName
	 *            Name of the new branch.
	 */
	public void createBranch(String refName, String newRefName) throws IOException {
		RefUpdate updateRef;
		updateRef = repository.updateRef(newRefName);
		Ref startRef = repository.getRef(refName);
		ObjectId startAt = repository.resolve(refName);
		String startBranch;
		if (startRef != null) {
			startBranch = refName;
		} else {
			startBranch = startAt.name();
		}
		startBranch = Repository.shortenRefName(startBranch);
		updateRef.setNewObjectId(startAt);
		updateRef.setRefLogMessage("branch: Created from " + startBranch, false);
		updateRef.update();
	}

	/**
	 * Checkouts branch.
	 * 
	 * @param refName
	 *            Full name of the branch.
	 */
	public void checkoutBranch(String refName) throws CoreException {
		new BranchOperation(repository, refName).execute(null);
	}

	/**
	 * Dispose of this wrapper along with its underlying repository.
	 */
	public void dispose() {
		if (repository != null) {
			repository.close();
			repository = null;
		}
	}

	/**
	 * Simulate a comparison between the two given references and returns back the subscriber that can provide
	 * all computed synchronization information.
	 * 
	 * @param sourceRef
	 *            Source reference (i.e. "left" side of the comparison).
	 * @param targetRef
	 *            Target reference (i.e. "right" side of the comparison).
	 * @param comparedFile
	 *            The file we are comparing (that would be the file right-clicked into the workspace).
	 * @return The created subscriber.
	 */
	public Subscriber createSubscriberForComparison(String sourceRef, String targetRef, IFile comparedFile)
			throws IOException {
		final GitSynchronizeData data = new GitSynchronizeData(repository, sourceRef, targetRef, false);
		final GitSynchronizeDataSet dataSet = new GitSynchronizeDataSet(data);
		final ResourceMapping[] mappings = getResourceMappings(comparedFile);
		GitResourceVariantTreeSubscriber subscriber = new GitResourceVariantTreeSubscriber(dataSet);
		subscriber.init(new NullProgressMonitor());

		final RemoteResourceMappingContext remoteContext = new GitSubscriberResourceMappingContext(
				subscriber, dataSet);
		final SubscriberScopeManager manager = new SubscriberScopeManager(subscriber.getName(), mappings,
				subscriber, remoteContext, true);
		final GitSubscriberMergeContext context = new GitSubscriberMergeContext(subscriber, manager, dataSet);
		return context.getSubscriber();
	}

	private String getRepoRelativePath(String path) {
		final int pfxLen = workdirPrefix.length();
		final int pLen = path.length();
		if (pLen > pfxLen) {
			return path.substring(pfxLen);
		} else if (path.length() == pfxLen - 1) {
			return "";
		}
		return null;
	}

	/**
	 * This will query all model providers for those that are enabled on the given file and list all mappings
	 * available for that file.
	 * 
	 * @param file
	 *            The file for which we need the associated resource mappings.
	 * @return All mappings available for that file.
	 */
	private static ResourceMapping[] getResourceMappings(IFile file) {
		final IModelProviderDescriptor[] modelDescriptors = ModelProvider.getModelProviderDescriptors();

		final Set<ResourceMapping> mappings = new LinkedHashSet<ResourceMapping>();
		for (IModelProviderDescriptor candidate : modelDescriptors) {
			try {
				final IResource[] resources = candidate.getMatchingResources(new IResource[] {file, });
				if (resources.length > 0) {
					// get mappings from model provider if there are matching resources
					final ModelProvider model = candidate.getModelProvider();
					final ResourceMapping[] modelMappings = model.getMappings(file,
							ResourceMappingContext.LOCAL_CONTEXT, null);
					for (ResourceMapping mapping : modelMappings) {
						mappings.add(mapping);
					}
				}
			} catch (CoreException e) {
				Activator.logError(e.getMessage(), e);
			}
		}
		return mappings.toArray(new ResourceMapping[mappings.size()]);
	}
}

Back to the top