Skip to main content
summaryrefslogtreecommitdiffstats
blob: d2bfaf2d38f8d2181b9d8b30d7023d3a9ee5f601 (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
/*******************************************************************************
 * Copyright (c) 2016 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
 * 
 * Contributors:
 *     Obeo - initial API and implementation
 *******************************************************************************/
package org.eclipse.emf.compare.ide.ui.tests.git.framework.internal.statements;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
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.egit.core.Activator;
import org.eclipse.egit.core.op.ConnectProviderOperation;
import org.eclipse.egit.core.op.DisconnectProviderOperation;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.ui.dialogs.IOverwriteQuery;
import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider;
import org.eclipse.ui.wizards.datatransfer.ImportOperation;

/**
 * This class contains utility methods to perform git tests. Those methods are internal and are not intended
 * to be used by clients.
 * 
 * @author <a href="mailto:mathieu.cartaud@obeo.fr">Mathieu Cartaud</a>
 */
@SuppressWarnings({"restriction" })
public class InternalGitTestSupport {

	/** The prefix of Git branches. */
	private static final String GIT_BRANCH_PREFIX = "refs/heads/"; //$NON-NLS-1$

	/** Name of the Eclipse metadata folder. */
	private static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$

	/** Size of the buffer to read/write data. */
	private static final int BUFFER_SIZE = 4096;

	/** The JGit repository. */
	protected Repository repository;

	/** The list of projects in the repository. */
	protected IProject[] projects;

	/** The list of JGit disposers. */
	protected ArrayList<Runnable> disposers;

	/** Query used to specify if the projects import must override existing projects. */
	private IOverwriteQuery overwriteQuery = new IOverwriteQuery() {
		public String queryOverwrite(String file) {
			return ALL;
		}
	};

	/**
	 * Adapt the given <code>branch</code> name to be in a correct format for Git or return it directly if it
	 * is already the case.
	 * 
	 * @param branch
	 *            The branch name we want to normalize
	 * @return the branch in Git format
	 */
	protected static String normalizeBranch(String branch) {
		if (branch.startsWith(GIT_BRANCH_PREFIX)) {
			return branch;
		} else {
			return GIT_BRANCH_PREFIX + branch;
		}
	}

	/**
	 * Perform all loading actions (unzip the archive, connect the git repository to JGit, import the
	 * contained projects in the workspace and connect them through JGit).
	 * 
	 * @param clazz
	 *            The test class
	 * @param path
	 *            The path of the archive containing the Git repository
	 * @throws Exception
	 *             If something goes wrong during unzip or import steps
	 */
	protected void createRepositoryFromPath(Class<?> clazz, String path) throws Exception {
		final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		// Delete all projects that can remain in the workspace : prevent errors dues to wrong cleanup of
		// other tests
		root.delete(true, new NullProgressMonitor());
		IPath location = root.getLocation();
		extractArchive(clazz, path, root);
		importProjects(new File(location.toString()));
		connectRepository(new File(location.toString()));
		projects = root.getProjects();
		for (IProject project : projects) {
			connect(project);
		}
	}

	/**
	 * Connect a project to the Git repository.
	 * 
	 * @param project
	 *            The project to connect
	 * @throws CoreException
	 *             Thrown if the project cannot be connected to the workspace
	 * @throws InterruptedException
	 *             Thrown if the operation is interrupted
	 */
	private void connect(IProject project) throws CoreException, InterruptedException {
		ConnectProviderOperation op = new ConnectProviderOperation(project, repository.getDirectory());
		op.execute(null);
	}

	/**
	 * Connect the Git repository to JGit.
	 * 
	 * @param file
	 *            The path to the root of the repository
	 * @throws IOException
	 *             If their is a problem during the connection to JGit
	 */
	private void connectRepository(File file) throws IOException {
		File gitDir = findGitDir(file);
		this.repository = Activator.getDefault().getRepositoryCache().lookupRepository(gitDir);
		this.disposers = new ArrayList<Runnable>();
	}

	/**
	 * Find the ".git" folder in the repository.
	 * 
	 * @param file
	 *            The path of the root of the unziped files
	 * @return The path to the .git folder
	 */
	private File findGitDir(File file) {
		File[] listFiles = file.listFiles();
		if (listFiles != null) {
			for (File child : listFiles) {
				if (child.isDirectory() && child.getName().equals(".git")) { //$NON-NLS-1$
					return child;
				} else if (child.isDirectory()) {
					File findGitDir = findGitDir(child);
					if (findGitDir != null) {
						return findGitDir;
					}
				}
			}
		}
		return null;
	}

	/**
	 * Import the Eclipse projects contained in the given file.
	 * 
	 * @param file
	 *            The folder to look inside
	 * @throws InvocationTargetException
	 *             Thrown if an error happen during the import of the project
	 * @throws InterruptedException
	 *             Thrown if the import operation is interrupted
	 * @throws CoreException
	 *             Thrown if the project cannot be created in the workspace
	 */
	private void importProjects(File file)
			throws InvocationTargetException, InterruptedException, CoreException {
		File[] listFiles = file.listFiles();
		if (listFiles != null) {
			for (File child : listFiles) {
				if (child.isDirectory() && !child.getName().equals(METADATA_FOLDER)
						&& !child.getName().equals(".git")) { //$NON-NLS-1$
					importProjects(child);
				} else if (child.getName().equals(".project")) { //$NON-NLS-1$
					importProject(child);
				}
			}
		}
	}

	/**
	 * Import the project located in the given path into the test workspace.
	 * 
	 * @param file
	 *            The path to the .project file
	 * @throws InvocationTargetException
	 *             Thrown if an error happen during the import of the project
	 * @throws InterruptedException
	 *             Thrown if the import operation is interrupted
	 * @throws CoreException
	 *             Thrown if the project cannot be created in the workspace
	 */
	private void importProject(File file)
			throws InvocationTargetException, InterruptedException, CoreException {
		IProjectDescription description = ResourcesPlugin.getWorkspace()
				.loadProjectDescription(new Path(file.getAbsolutePath()));
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(description.getName());
		project.create(description, new NullProgressMonitor());
		project.open(new NullProgressMonitor());

		ImportOperation importOperation = new ImportOperation(project.getFullPath(), file.getParentFile(),
				FileSystemStructureProvider.INSTANCE, overwriteQuery);
		importOperation.setCreateContainerStructure(false);
		importOperation.run(new NullProgressMonitor());
	}

	/**
	 * Extract the zip file into the given workspace.
	 * 
	 * @param clazz
	 *            The test class
	 * @param path
	 *            The path to the archive (relative to the test class)
	 * @param root
	 *            The root of the test workspace
	 * @throws IOException
	 *             Thrown if the zip extraction goes wrong
	 */
	private void extractArchive(Class<?> clazz, String path, IWorkspaceRoot root) throws IOException {
		try (InputStream resourceAsStream = clazz.getResourceAsStream(path);
				ZipInputStream zipIn = new ZipInputStream(resourceAsStream);) {
			ZipEntry entry = null;
			while ((entry = zipIn.getNextEntry()) != null) {
				String filePath = root.getLocation() + File.separator + entry.getName();
				if (!entry.isDirectory()) {
					extractFile(zipIn, filePath);
				} else {
					File dir = new File(filePath);
					dir.mkdir();
				}
				zipIn.closeEntry();
			}
		}
	}

	/**
	 * Extract the given input stream to the given location.
	 * 
	 * @param zipIn
	 *            The zip input stream
	 * @param filePath
	 *            The destination path for the extraction
	 * @throws IOException
	 *             Thrown if something happen during the extraction
	 */
	private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));) {
			byte[] bytesIn = new byte[BUFFER_SIZE];
			int read = 0;
			while ((read = zipIn.read(bytesIn)) != -1) {
				bos.write(bytesIn, 0, read);
			}
		}
	}

	/**
	 * Clean all possibly remaining elements to start the test in a clean state.
	 * 
	 * @throws CoreException
	 *             Thrown if a project cannot be deleted
	 * @throws IOException
	 *             Thrown if a file cannot be deleted
	 */
	protected void setup() throws CoreException, IOException {
		final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
		IProject[] unknownProjects = workspaceRoot.getProjects();
		if (unknownProjects != null && unknownProjects.length > 0) {
			for (IProject iProject : unknownProjects) {
				iProject.delete(true, new NullProgressMonitor());
			}
		}
		Activator.getDefault().getRepositoryCache().clear();

		File file = new File(workspaceRoot.getLocation().toOSString());
		File[] listFiles = file.listFiles();
		if (listFiles != null) {
			for (File child : listFiles) {
				if (!child.getName().equals(METADATA_FOLDER)) {
					try (Stream<java.nio.file.Path> walk = Files.walk(child.toPath())) {
						walk.sorted(Comparator.reverseOrder()).map(java.nio.file.Path::toFile)
								.forEach(File::delete);
					}
				}
			}
		}
	}

	/**
	 * Clear workspace and repository for next tests.
	 * 
	 * @throws CoreException
	 *             Thrown if a project cannot be deleted
	 * @throws IOException
	 *             Thrown if a file cannot be deleted
	 */
	protected void tearDown() throws CoreException, IOException {
		if (repository != null) {
			repository.close();
			repository = null;
		}
		if (disposers != null) {
			for (Runnable disposer : disposers) {
				disposer.run();
			}
			disposers.clear();
		}

		Activator.getDefault().getRepositoryCache().clear();

		if (projects != null) {
			new DisconnectProviderOperation(Arrays.asList(projects)).execute(null);
			for (IProject iProject : projects) {
				iProject.delete(true, new NullProgressMonitor());
			}
			ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE,
					new NullProgressMonitor());
		}

		File file = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());
		File[] listFiles = file.listFiles();
		if (listFiles != null) {
			for (File child : listFiles) {
				if (!child.getName().equals(METADATA_FOLDER)) {
					try (Stream<java.nio.file.Path> walk = Files.walk(child.toPath())) {
						walk.sorted(Comparator.reverseOrder()).map(java.nio.file.Path::toFile)
								.forEach(File::delete);
					}
				}
			}
		}
	}

}

Back to the top