Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 6719fd0465a7763770c6f33eef80a9d292712dda (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
/*******************************************************************************
 * Copyright (C) 2009, Mykola Nikishov <mn@mn.com.ua>
 * Copyright (C) 2011, Robin Stocker <robin@nibor.org>
 *
 * 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.egit.core;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
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.IProgressMonitor;
import org.eclipse.egit.core.op.CloneOperation;
import org.eclipse.egit.core.op.ConnectProviderOperation;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.osgi.util.NLS;
import org.eclipse.team.core.ProjectSetCapability;
import org.eclipse.team.core.ProjectSetSerializationContext;
import org.eclipse.team.core.TeamException;

/**
 * Capability for exporting and importing projects shared with Git as part of a
 * team project set.
 */
public final class GitProjectSetCapability extends ProjectSetCapability {

	private static final String SEPARATOR = ","; //$NON-NLS-1$
	private static final String VERSION = "1.0"; //$NON-NLS-1$

	private static final class ProjectReferenceComparator implements
			Comparator<ProjectReference>, Serializable {
		private static final long serialVersionUID = 1L;

		public int compare(ProjectReference o1, ProjectReference o2) {
			final boolean reposEqual = o1.repository.equals(o2.repository);
			final boolean branchesEqual = o1.branch
					.equals(o2.branch);
			final boolean projectDirsEqual = o1.projectDir
					.equals(o2.projectDir);
			return reposEqual && branchesEqual && projectDirsEqual ? 0 : 1;
		}
	}

	private static final class ProjectReference {

		private static final String DEFAULT_BRANCH = Constants.MASTER;

		/**
		 * a relative path (from the repository root) to a project
		 */
		String projectDir;

		/**
		 * <code>repository</code> parameter
		 */
		URIish repository;

		/**
		 * the remote branch that will be checked out, see <code>--branch</code>
		 * option
		 */
		String branch = DEFAULT_BRANCH;

		@SuppressWarnings("boxing")
		ProjectReference(final String reference) throws URISyntaxException, IllegalArgumentException {
			final String[] tokens = reference.split(Pattern.quote(SEPARATOR));
			if (tokens.length != 4)
				throw new IllegalArgumentException(NLS.bind(
						CoreText.GitProjectSetCapability_InvalidTokensCount, new Object[] {
								4, tokens.length, tokens }));

			this.repository = new URIish(tokens[1]);
			if (!"".equals(tokens[2])) //$NON-NLS-1$
				this.branch = tokens[2];
			this.projectDir = tokens[3];
		}
	}

	@Override
	public String[] asReference(IProject[] projects,
			ProjectSetSerializationContext context, IProgressMonitor monitor)
			throws TeamException {
		String[] references = new String[projects.length];
		for (int i = 0; i < projects.length; i++)
			references[i] = asReference(projects[i]);
		return references;
	}

	private String asReference(IProject project) throws TeamException {
		RepositoryMapping mapping = RepositoryMapping.getMapping(project);
		String branch;
		try {
			branch = mapping.getRepository().getBranch();
		} catch (IOException e) {
			throw new TeamException(NLS.bind(
					CoreText.GitProjectSetCapability_ExportCouldNotGetBranch,
					project.getName()));
		}
		StoredConfig config = mapping.getRepository().getConfig();
		String remote = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
				branch, ConfigConstants.CONFIG_KEY_REMOTE);
		String url = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION,
				remote, ConfigConstants.CONFIG_KEY_URL);
		if (url == null)
			throw new TeamException(NLS.bind(
					CoreText.GitProjectSetCapability_ExportNoRemote,
					project.getName()));

		String projectPath = mapping.getRepoRelativePath(project);
		if (projectPath.equals("")) //$NON-NLS-1$
			projectPath = "."; //$NON-NLS-1$

		StringBuilder sb = new StringBuilder();

		sb.append(VERSION);
		sb.append(SEPARATOR);
		sb.append(url);
		sb.append(SEPARATOR);
		sb.append(branch);
		sb.append(SEPARATOR);
		sb.append(projectPath);

		return sb.toString();
	}

	@Override
	public IProject[] addToWorkspace(final String[] referenceStrings,
			final ProjectSetSerializationContext context,
			final IProgressMonitor monitor) throws TeamException {
		final Map<URIish, Map<String, Set<ProjectReference>>> repositories =
				new LinkedHashMap<URIish, Map<String, Set<ProjectReference>>>();
		for (final String reference : referenceStrings) {
			try {
				final ProjectReference projectReference = new ProjectReference(
						reference);
				Map<String, Set<ProjectReference>> repositoryBranches = repositories
						.get(projectReference.repository);
				if (repositoryBranches == null) {
					repositoryBranches = new HashMap<String, Set<ProjectReference>>();
					repositories.put(projectReference.repository,
							repositoryBranches);
				}
				Set<ProjectReference> projectReferences = repositoryBranches.get(projectReference.branch);
				if (projectReferences == null) {
					projectReferences = new TreeSet<ProjectReference>(new ProjectReferenceComparator());
					repositoryBranches.put(projectReference.branch, projectReferences);
				}

				projectReferences.add(projectReference);
			} catch (final IllegalArgumentException e) {
				throw new TeamException(reference, e);
			} catch (final URISyntaxException e) {
				throw new TeamException(reference, e);
			}
		}
		final ArrayList<IProject> importedProjects = new ArrayList<IProject>();
		for (final Map.Entry<URIish, Map<String, Set<ProjectReference>>> entry : repositories.entrySet()) {
			final URIish gitUrl = entry.getKey();
			final Map<String, Set<ProjectReference>> branches = entry.getValue();

			for (final Map.Entry<String, Set<ProjectReference>> branchEntry : branches.entrySet()) {
				final String branch = branchEntry.getKey();
				final Set<ProjectReference> projects = branchEntry.getValue();

				try {
					final IPath workDir = getWorkingDir(gitUrl, branch,
							branches.keySet());
					if (workDir.toFile().exists()) {
						final Collection<String> projectNames = new LinkedList<String>();
						for (final ProjectReference projectReference : projects)
							projectNames.add(projectReference.projectDir);
						throw new TeamException(NLS.bind(
								CoreText.GitProjectSetCapability_CloneToExistingDirectory,
								new Object[] { workDir, projectNames, gitUrl }));
					}

					int timeout = 60;
					String refName = Constants.R_HEADS + branch;
					final CloneOperation cloneOperation = new CloneOperation(
							gitUrl, true, null, workDir.toFile(), refName,
							Constants.DEFAULT_REMOTE_NAME, timeout);
					cloneOperation.run(monitor);

					final File repositoryPath = workDir.append(Constants.DOT_GIT_EXT).toFile();

					Activator.getDefault().getRepositoryUtil().addConfiguredRepository(repositoryPath);

					// import projects from the current repository to workspace
					final IWorkspace workspace = ResourcesPlugin.getWorkspace();
					final IWorkspaceRoot root = workspace.getRoot();
					for (final ProjectReference projectToImport : projects) {
						final IPath projectDir = workDir
								.append(projectToImport.projectDir);
						final IProjectDescription projectDescription = workspace
								.loadProjectDescription(projectDir
										.append(IProjectDescription.DESCRIPTION_FILE_NAME));
						final IProject project = root
								.getProject(projectDescription.getName());
						project.create(projectDescription, monitor);
						importedProjects.add(project);

						project.open(monitor);
						final ConnectProviderOperation connectProviderOperation = new ConnectProviderOperation(
								project, repositoryPath);
						connectProviderOperation.execute(monitor);
					}
				} catch (final InvocationTargetException e) {
					throw TeamException.asTeamException(e);
				} catch (final CoreException e) {
					throw TeamException.asTeamException(e);
				} catch (final InterruptedException e) {
					// was canceled by user
					return new IProject[0];
				}
			}
		}
		final IProject[] result = importedProjects
				.toArray(new IProject[importedProjects.size()]);
		return result;
	}

	/**
	 * @param gitUrl
	 * @param branch the branch to check out
	 * @param allBranches all branches which should be checked out for this gitUrl
	 * @return the directory where the project should be checked out
	 */
	private static IPath getWorkingDir(URIish gitUrl, String branch, Set<String> allBranches) {
		final IPath workspaceLocation = ResourcesPlugin.getWorkspace()
				.getRoot().getRawLocation();
		final String humanishName = gitUrl.getHumanishName();
		String extendedName;
		if (allBranches.size() == 1 || branch.equals(Constants.MASTER))
			extendedName = humanishName;
		else
			extendedName = humanishName + "_" + branch; //$NON-NLS-1$
		final IPath workDir = workspaceLocation.append(extendedName);
		return workDir;
	}

}

Back to the top