Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 66772afd2c77b1b3563a7fe9851e9beeb596edf1 (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
/*****************************************************************************
 * Copyright (c) 2016 Christian W. Damus 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:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.dev.project.management.handlers;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.papyrus.dev.project.management.Activator;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.statushandlers.StatusManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Ensures that <tt>pom.xml</tt> files have the same version number as their
 * corresponding <tt>MANIFEST.MF</tt> or <tt>feature.xml</tt> file.
 * 
 * @since 1.2
 */
public class SyncManifestAndPOMVersions extends AbstractHandler {
	private static final Pattern BUNDLE_VERSION = Pattern.compile("^Bundle-Version:\\s*(\\S+)\\s*$", Pattern.MULTILINE); //$NON-NLS-1$
	private static final Pattern POM_FIXUP = Pattern.compile("^(<\\?xml\\s.*?\\?>)\\s*(<project>)\\s*$", Pattern.MULTILINE);

	public SyncManifestAndPOMVersions() {
		super();
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Map<IFile, IFile> pomsByManifest = getAllPOMsByManifest();

		ISchedulingRule[] rules = Stream.concat(
				pomsByManifest.keySet().stream(),
				pomsByManifest.values().stream()).toArray(ISchedulingRule[]::new);
		MultiRule jobRule = new MultiRule(rules);

		Job updateJob = new Job("Synchronize POM versions") {

			{
				setRule(jobRule);
			}

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				SubMonitor sub = SubMonitor.convert(monitor, "Updating POMs...", pomsByManifest.size());

				pomsByManifest.forEach((manifest, pom) -> {
					try {
						if (sub.isCanceled()) {
							throw new OperationCanceledException();
						}

						String version = getVersion(manifest);
						if (version != null) {
							version = version.replace(".qualifier", "-SNAPSHOT"); //$NON-NLS-1$//$NON-NLS-2$
							Document xml = slurpXML(pom);
							Element versionElement = findVersion(xml);
							if (versionElement != null) {
								if (!version.equals(versionElement.getTextContent())) {
									versionElement.setTextContent(version);
									write(xml, pom);
								}
							}
						}

						sub.worked(1);
					} catch (CoreException e) {
						StatusManager.getManager().handle(e.getStatus(), StatusManager.SHOW);
					}
				});

				sub.done();

				return Status.OK_STATUS;
			}
		};
		updateJob.schedule();

		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IProgressService progress = window.getWorkbench().getProgressService();
		progress.showInDialog(window.getShell(), updateJob);

		return null;
	}

	Map<IFile, IFile> getAllPOMsByManifest() {
		Map<IFile, IFile> result = new HashMap<>();

		Stream.of(ResourcesPlugin.getWorkspace().getRoot().getProjects())
				.filter(this::hasPluginOrFeatureNature)
				.forEach(project -> {
					IFile pom = project.getFile("pom.xml"); //$NON-NLS-1$
					if ((pom != null) && pom.isAccessible()) {
						IFile manifest = project.getFile("feature.xml");
						if (!manifest.isAccessible()) {
							manifest = project.getFile("META-INF/MANIFEST.MF");
						}

						if (manifest.isAccessible()) {
							result.put(manifest, pom);
						}
					}
				});

		return result;
	}

	String slurpText(IFile file) throws CoreException {
		StringBuilder result = new StringBuilder();
		CharBuffer buf = CharBuffer.allocate(4096);

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getContents(), Charset.forName(file.getCharset())))) {
			for (;;) {
				if (reader.read(buf) < 0) {
					break; // Done
				}
				buf.flip();
				result.append(buf);
				buf.rewind();
			}
		} catch (IOException e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to read manifest", e));
		}

		return result.toString();
	}

	Document slurpXML(IFile xmlFile) throws CoreException {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			try (InputStream input = xmlFile.getContents()) {
				return builder.parse(input);
			}
		} catch (Exception e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to read manifest file", e)); //$NON-NLS-1$
		}
	}

	void write(Document xml, IFile xmlFile) throws CoreException {
		try (StringWriter writer = new StringWriter()) {
			Transformer transformer = TransformerFactory.newInstance().newTransformer();

			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			xml.setXmlStandalone(true);
			xml.setXmlVersion("1.0");

			Result result = new StreamResult(writer);
			transformer.transform(new DOMSource(xml), result);
			String text = writer.toString();

			// Fix up the transformer's sometime failure to put a newline after the XML declaration
			Matcher fixup = POM_FIXUP.matcher(text);
			if (fixup.find()) {
				StringBuffer fixed = new StringBuffer(text.length() + 2);
				fixup.appendReplacement(fixed, fixup.group(1) + '\n' + fixup.group(2));
				fixup.appendTail(fixed);
				text = fixed.toString();
			}

			// Write it out
			ByteArrayInputStream input = new ByteArrayInputStream(text.getBytes(Charset.forName("UTF-8"))); //$NON-NLS-1$
			xmlFile.setContents(input, false, true, null);
		} catch (Exception e) {
			throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to update POM", e));
		}
	}

	String getVersion(IFile manifest) throws CoreException {
		String result = null;

		switch (manifest.getName()) {
		case "MANIFEST.MF": //$NON-NLS-1$
			String text = slurpText(manifest);
			Matcher m = BUNDLE_VERSION.matcher(text);
			if (m.find()) {
				result = m.group(1);
			}
			break;
		case "feature.xml": //$NON-NLS-1$
			Document xml = slurpXML(manifest);
			result = xml.getDocumentElement().getAttribute("version"); //$NON-NLS-1$
		}

		return result;
	}

	Element findVersion(Document pom) {
		Element project = pom.getDocumentElement();
		return stream(project.getChildNodes())
				.filter(n -> "version".equals(n.getNodeName()))
				.filter(Element.class::isInstance).map(Element.class::cast)
				.findFirst().orElse(null);
	}

	Stream<Node> stream(NodeList nodes) {
		Stream.Builder<Node> result = Stream.builder();
		for (int i = 0; i < nodes.getLength(); i++) {
			result.add(nodes.item(i));
		}
		return result.build();
	}

	boolean hasPluginOrFeatureNature(IProject project) {
		boolean result = false;

		if (project.isAccessible()) {
			try {
				IProjectDescription desc = project.getDescription();
				List<String> natures = Arrays.asList(desc.getNatureIds());
				result = natures.contains("org.eclipse.pde.PluginNature") //$NON-NLS-1$
						|| natures.contains("org.eclipse.pde.FeatureNature"); //$NON-NLS-1$
			} catch (CoreException e) {
				// Guess it's not an interesting project
				Activator.log.log(e.getStatus());
			}
		}

		return result;
	}
}

Back to the top